#pragma once

#include <iostream>
#include <unordered_map>
#include <functional>
#include <ctime>
#include <sys/types.h>
#include <unistd.h>

using task_t = std::function<void()>;

void DownLoad()
{
    std::cout << "我是下载任务..., pid" << getpid() << std::endl;
}

void Log()
{
    std::cout << "我是日志任务..., pid" << getpid() << std::endl;
}
void Sql()
{
    std::cout << "我是数据库同步任务..., pid" << getpid() << std::endl;
}



static int number = 0;
class TaskManger
{
public:
    TaskManger()
    {
        srand(time(nullptr));
        InsertTask(DownLoad);
        InsertTask(Log);
        InsertTask(Sql);
    }
    void InsertTask(task_t t)
    {
        tasks[number++] = t;
    }
    int SelectTask()
    {
        return rand() % number;
    }
    void Excute(int number)
    {
        if(tasks.find(number) == tasks.end()) return; //没找到
        tasks[number](); //s
    }
    ~TaskManger()
    {}

private:
    std::unordered_map<int, task_t> tasks;
};

TaskManger tm;


void Worker() // 子进程要完成的任务都在这里面
{
    // read -> 0
    while (true)
    {
        int cmd = 0;
        int n = ::read(0, &cmd, sizeof(cmd));
        if(n == sizeof(cmd)) // 读取成功
        {
            tm.Excute(cmd);
        }
        else if(n == 0)
        {
            std::cout << "pid: " << getpid() << " quit..." << std::endl;
            break;
        }
        else
        {
            
        }
    }
    

    //sleep(10);
}